package myJs

import myJs.Implicits._
import myJs.Utils._

import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg.LayerOptions
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.Event
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all.s

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("RecoverPassword")
object RecoverPassword {

  @JSExport("init")
  def init = {
    bootStrapValidator
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "name" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "blank" -> js.Dictionary()
            )
          )
        } ,
        "captcha" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "blank" -> js.Dictionary()
            )
          )
        } ,
      )
    )
    $(s"#form").bootstrapValidator(dict).on("success.form.bv", (e: Event) => {
      e.preventDefault()
      val bv = $(s"#form").bv
      val res = g.verifyCode.validate($("#captcha").`val`())
      val b = res.toString.toBoolean
      if (b) {
        val url = g.jsRoutes.controllers.AppController.validName().url.toString
        val formData = $(s"#form").serialize()
        Ajax.post(url = s"${url}", data = formData, headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
          val rs = xhr.responseText
          val valid = rs.toBoolean
          if (valid) {
            bv.defaultSubmit()
          } else {
            bv.updateMessage("name", "blank", messages("theAccountDoesNotExist"))
            bv.updateStatus("name", "INVALID", "blank")
            g.verifyCode.refresh()
            $("#captcha").`val`("")
          }
        }
      } else {
        bv.updateMessage("captcha", "blank", messages("ErrorInVerificationCode"))
        bv.updateStatus("captcha", "INVALID", "blank")
      }
    })
  }


}
